﻿using MzkUi;
using NAudio.Wave;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using static MzkMusic.Interface;
using static System.Net.Mime.MediaTypeNames;

namespace MzkMusic
{
    public partial class MainForm : Form
    {
        private bool isMenuOpen = true; // 菜单是否打开
        private IWavePlayer waveOut;
        private AudioFileReader audioFileReader;
        UiSong CurPlayMusic = new UiSong();
        public MainForm()
        {
            InitializeComponent();
            LrcUi lrcUi = new LrcUi(MusicListPnl);
            lrcUi.Dock = DockStyle.Fill;
            lrcUi.Show();
            LrcPnl.Controls.Add(lrcUi);
        }
        private void MainForm_Load(object sender, EventArgs e)
        {
            CreateMusicList();
            // 搜索歌曲
            Button CheckMusicBtn = new Button();
            CheckMusicBtn.Text = "搜索歌曲";
            CheckMusicBtn.Click += CheckMusic_Click;
            CheckMusicBtn.Dock = DockStyle.Top;
            MusicListPnl.Controls.Add(CheckMusicBtn);
            // 创建当前播放
            CurPlayMusic.Dock = DockStyle.Fill;
            CurPlayMusic.Index = 0;
            CurPlayMusic.UiBtnClick += MusicPlay_Click;
            CurPlayMusic.UiMusicBtn += CurPlayMusic_Click;
            CurPlayMusicPnl.Controls.Add(CurPlayMusic);
        }
        private void CurPlayMusic_Click(object sender, EventArgs e)
        {
            if (MusicListPnl.Visible == true)
            {
                MusicListPnl.Visible = false;
                MusicListPnl.Dock = DockStyle.None;
                LrcPnl.Dock = DockStyle.Fill;
                LrcPnl.Visible = !MusicListPnl.Visible;
            }
        }
        private void CreateMusicList()
        {
            try
            {
                // 创建 歌单列表
                for (int i = 0; i < GlobalData.SongCount; i++)
                {
                    UiSong song = new UiSong();
                    song.uiProgressBar.MzkBarValueVisible = false;
                    song.uiProgressBar.Show();
                    song.uiProgressBar.Visible = false;
                    song.Size = new Size(MusicListPnl.Width, 22);
                    song.Dock = DockStyle.Top;
                    song.BackColor = Color.Transparent;
                    song.MusicAuthor.Text = GlobalData.SongList[i].Author;
                    song.Music.Text = GlobalData.SongList[i].Name;
                    song.MusicTime.Text = GlobalData.SongList[i].Time;
                    song.Index = i + 1;
                    song.Name = "UiSong" + (i + 1).ToString();
                    song.UiBtnClick += MusicPlay_Click;
                    song.BorderStyle = BorderStyle.Fixed3D;
                    MusicListPnl.Controls.Add(song);
                }
            }
            catch  (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }
        private void PlayMp3(string filePath)
        {
            if (waveOut != null)
            {
                StopMp3(); // 如果正在播放，先停止
            }

            audioFileReader = new AudioFileReader(filePath);
            waveOut = new WaveOutEvent();
            waveOut.PlaybackStopped += WaveOut_PlaybackStopped;
            waveOut.Init(audioFileReader);
            waveOut.Play();
            RefreshTime.Start();
            GlobalData.CurPlayStart = true;
        }
        private void WaveOut_PlaybackStopped(object sender, StoppedEventArgs e)
        {
        }
        private void StopMp3()
        {
            RefreshTime.Stop();
            if (waveOut != null)
            {
                waveOut.Stop();
                waveOut.Dispose();
                waveOut = null;
            }

            if (audioFileReader != null)
            {
                audioFileReader.Dispose();
                audioFileReader = null;
            }
            GlobalData.CurPlayStart = false;
        }
        public Double GetCurrentTime()
        {
            if (audioFileReader == null)
            {
                return 00.00; // 如果没有正在播放的音频，返回0秒
            }
            // 计算当前播放时间（以秒为单位）
            double currentTimeInSeconds = audioFileReader.Position / (double)audioFileReader.WaveFormat.AverageBytesPerSecond;
            // 格式化时间为00.00
            return currentTimeInSeconds;
            // 将时间转换为TimeSpan对象
            //TimeSpan currentTime = TimeSpan.FromSeconds(currentTimeInSeconds);
            //return currentTime.ToString("mm\\.ss");
        }
        public double GetPlaybackProgress()
        {
            if (audioFileReader == null || audioFileReader.Length == 0)
            {
                return 0.0; // 如果没有正在播放的音频，返回0%
            }

            // 计算播放进度百分比
            double progress = (audioFileReader.Position / (double)audioFileReader.Length) * 100.0;
            return progress;
        }
        private void CurrentPlayMusicInit(SongInfo songInfo, bool start)
        {
            // 刷新控件
            CurPlayMusic.MusicAuthor.Text = songInfo.Author;
            CurPlayMusic.MusicTime.Text= songInfo.Time;
            CurPlayMusic.Music.Text = songInfo.Name;
            CurPlayMusic.StartPlay = start;
            CurPlayMusic.Index = GlobalData.CurPlayMusicIndex;
            if (start) PlayMp3(songInfo.Path);
            else StopMp3();
            // 保存数据
            GlobalData.CurPlayMusic.Author = songInfo.Author; 
            GlobalData.CurPlayMusic.Path = songInfo.Path;
            GlobalData.CurPlayMusic.Name = songInfo.Name;
            GlobalData.CurPlayMusic.Time = songInfo.Time;
            GlobalData.CurPlayMusic.lyrics = songInfo.lyrics;
        }
        private void MusicPlay_Click(object sender, EventArgs e)
        {
            Button button = (Button) sender;
            UiSong uiSong = (UiSong)button.Parent.Parent;
            int MusicIndex = uiSong.Index;
            if (GlobalData.SongCount <= 0)
            {
                MessageBox.Show("歌单中没有歌曲！请先添加", "提示", MessageBoxButtons.OK, MessageBoxIcon.Hand);
                uiSong.StartPlay = false;
                return;
            }
            string SongName;
            UiSong uiSongx;
            switch (button.Name) // FavoriteMusicBtn， PrevMusicBtn ，NextMusicBtn， MusicStartBtn
            {
                case "FavoriteMusicBtn":
                    break;
                case "PrevMusicBtn":
                    // 关闭当前播放歌曲  
                    if (MusicIndex != 0)
                    {
                        SongName = "UiSong" + MusicIndex.ToString();
                        uiSongx = (UiSong)FindControl(MusicListPnl, SongName);
                        if (uiSongx != null) uiSongx.StartPlay = false;
                    }
                    // 计算下一首 索引
                    if (MusicIndex == GlobalData.SongCount) MusicIndex = 1;
                    else  MusicIndex += 1;
                    // 查找下一首
                    SongName = "UiSong" + MusicIndex.ToString();
                    uiSongx = (UiSong)FindControl(MusicListPnl, SongName);
                    if (uiSongx != null) uiSongx.StartPlay = true;
                    // 播放
                    CurrentPlayMusicInit(GlobalData.SongList[MusicIndex - 1], uiSongx.StartPlay);
                    GlobalData.CurPlayMusicIndex = MusicIndex;
                    break;
                case "NextMusicBtn":
                    // 关闭当前播放歌曲  
                    if (MusicIndex != 0)
                    {
                        SongName = "UiSong" + MusicIndex.ToString();
                        uiSongx = (UiSong)FindControl(MusicListPnl, SongName);
                        if (uiSongx != null) uiSongx.StartPlay = false;
                    }
                    // 计算下一首 索引
                    if (MusicIndex == 1) MusicIndex = GlobalData.SongCount;
                    else MusicIndex -= 1;
                    // 查找下一首
                    SongName = "UiSong" + MusicIndex.ToString();
                    uiSongx = (UiSong)FindControl(MusicListPnl, SongName);
                    if (uiSongx != null) uiSongx.StartPlay = true;
                    // 播放
                    CurrentPlayMusicInit(GlobalData.SongList[MusicIndex - 1], uiSongx.StartPlay);
                    GlobalData.CurPlayMusicIndex = MusicIndex;
                    break;
                case "MusicStartBtn":
                    // 点击非当前播放歌曲  关闭上一首歌曲
                    if (GlobalData.CurPlayMusicIndex > 0 && GlobalData.CurPlayMusicIndex != MusicIndex && MusicIndex != 0)
                    {
                        SongName = "UiSong" + GlobalData.CurPlayMusicIndex.ToString();
                        uiSongx = (UiSong)FindControl(MusicListPnl, SongName);
                        if (uiSongx != null)
                            uiSongx.StartPlay = false;
                    }
                    // 在歌曲菜单中点击相同歌曲
                    else if (GlobalData.CurPlayMusicIndex > 0 && GlobalData.CurPlayMusicIndex == MusicIndex) // 恢复
                    {
                        MusicIndex = GlobalData.CurPlayMusicIndex;
                        SongName = "UiSong" + GlobalData.CurPlayMusicIndex.ToString();
                        uiSongx = (UiSong)FindControl(MusicListPnl, SongName);
                        if (uiSongx != null)
                            uiSongx.StartPlay = uiSong.StartPlay;
                    }
                    GlobalData.CurPlayMusicIndex = MusicIndex;
                    if (GlobalData.CurPlayMusicIndex == 0 && MusicIndex == 0)
                        return;
                    CurrentPlayMusicInit(GlobalData.SongList[MusicIndex-1], uiSong.StartPlay);
                    break;
            }
        }
        private void CheckMusic_Click(object sender, EventArgs e)
        {
            openFileDialog.Title = "选择音乐所在文件夹";
            openFileDialog.CheckFileExists = false; // 不检查文件是否存在
            openFileDialog.CheckPathExists = true; // 检查路径是否存在
            openFileDialog.Filter = "文件夹|"; // 设置为选择文件夹模式
            openFileDialog.RestoreDirectory = true;

            DialogResult result = openFileDialog.ShowDialog();
            if (result == DialogResult.OK)
            {
                // 获取选中的文件夹路径
                string selectedFolder = System.IO.Path.GetDirectoryName(openFileDialog.FileName);

                // 获取文件夹中所有的.mp3文件 路径
                string[] mp3Files = Directory.GetFiles(selectedFolder, "*.mp3");
                // 只获取名称不保留后缀和路径
                string[] fileNames = new string[mp3Files.Length];
                for (int i = 0; i < mp3Files.Length; i++)
                    fileNames[i] = Path.GetFileNameWithoutExtension(mp3Files[i]);
                GlobalData.SongCount = 0;
                // 检查是否有.mp3文件
                if (mp3Files.Length > 0)
                {
                    foreach (string file in mp3Files)
                    {
                        string title, artist, album, lyrics;
                        TimeSpan duration;
                        // 使用TagLib#加载文件
                        using (var F = TagLib.File.Create(file))
                        {
                            // 获取歌曲信息
                            title = F.Tag.Title; // 歌曲标题
                            artist = F.Tag.FirstPerformer; // 演唱者
                            album = F.Tag.Album; // 专辑
                            duration = F.Properties.Duration; // 时长
                            //lyrics = F.Tag.Lyrics.Length > 0 ? F.Tag.Lyrics : "该MP3文件中没有歌词。";
                            if (F.Tag.Lyrics != null)
                            {
                                lyrics = F.Tag.Lyrics;
                            }
                            else
                            {
                                string lrcFilePath = Path.ChangeExtension(mp3Files[GlobalData.SongCount], "lrc");
                                // 检查.lrc文件是否存在
                                if (File.Exists(lrcFilePath))
                                {
                                    // 读取.lrc文件内容
                                    lyrics = File.ReadAllText(lrcFilePath);
                                }
                                else
                                {
                                    lyrics = "无歌词";
                                }
                            } 
                        }
                        GlobalData.SongList[GlobalData.SongCount] = new Interface.SongInfo(artist, mp3Files[GlobalData.SongCount],
                            fileNames[GlobalData.SongCount], duration.ToString(@"mm\:ss"), lyrics, false, 0.00);
                        GlobalData.SongCount++;
                    }
                }
                MusicListPnl.Controls.Clear();
                MainForm_Load(null, null);
            }
        }
        // 递归查找控件
        public Control FindControl(Control container, string controlName)
        {
            foreach (Control ctrl in container.Controls)
            {
                if (ctrl.Name == controlName)
                {
                    return ctrl; // 找到了控件，返回
                }
                if (ctrl.HasChildren) // 如果当前控件有子控件，递归查找
                {
                    Control foundCtrl = FindControl(ctrl, controlName);
                    if (foundCtrl != null)
                    {
                        return foundCtrl; // 在子控件中找到了目标控件，返回
                    }
                }
            }
            return null; // 没有找到控件
        }
        private void MainForm_SizeChanged(object sender, EventArgs e)
        {
            if (MainPnl.Visible)
            {
                MainPnl.Width = this.Width/10*5;
            }
        }

        private void reflrash_Tick(object sender, EventArgs e)
        {
            GlobalData.CurPlayMusic.CurTime = GetCurrentTime();
            TimeSpan currentTime = TimeSpan.FromSeconds(GlobalData.CurPlayMusic.CurTime);
            CurPlayMusic.MusicTime.Text = currentTime.ToString("mm\\.ss");
            CurPlayMusic.uiProgressBar.MzkValue = (int)GetPlaybackProgress();

        }
    }
}